<template>
	<view class="content">
		<z-paging ref="paging" v-model="tableData" @query="searchDraft" :loading-more-enabled="false"
			loading-more-no-more-text="没有更多了" :use-virtual-list="true" :auto="false" :topZIndex="999" :bottomZIndex="10"
			auto-show-back-to-top :back-to-top-style="{ 'opacity':0.6 }">
			<template #top>
				<u-navbar :fixed="false" :title="titleName" :autoBack="false" :safeAreaInsetTop="true">
					<view slot="left" class="x-f">
						<u-icon name="arrow-left" color="#fff" size="20" @click="goBack"></u-icon>

						<u-icon name="close" color="#fff" size="20" style="margin-left: 20px;"
							@click="goBack('close')"></u-icon>
					</view>

					<view slot="right">
						<m-bubble type="list" :selectData="formMenus" position="right" topOpsotion="right"
							bgcRgba="#fff" color="#333" @selectFun="TapPopup">
							<u-icon name="more-dot-fill" color="#fff" class="moremenu"></u-icon>
						</m-bubble>
					</view>
				</u-navbar>
			</template>


			<template #cell="{item,index}">
				<view class="CellBox x-bc" hover-class="cellHover" :hover-stay-time="200" @click="toFormEdit(item)">
					<view class="x-f" style="flex:1;">
						<view class="ordinalBox">{{+index + 1}}</view>

						<text>{{item.CreatDate}}</text>
					</view>

					<view class="x-f" style="position: relative;">
						<view
							style="position: absolute;left: 0;top: 0;width: 100%;height:100%;z-index: 9;background-color: transparent;">
						</view>


						<checkbox v-if="ShowSelect" class="CheckBox" :checked="CheckedBack(item)" color="#fff"
							activeBackgroundColor="#51d0d0" activeBorderColor="#51d0d0">
						</checkbox>

						<uni-icons v-if="!ShowSelect" type="right" size="24" color="#999"></uni-icons>


					</view>
				</view>
			</template>


			<template #bottom>
				<view class="bottomTool x-bc" :style="$utils.disposeSafeBottomFun()">
					<view class="operTotal x-f" @click="OpenSelectCellPopup">

						<view v-if="!ShowSelect" class="FiledBox" style="width: fit-content;">
							<text class="FiledBox_grifola">
								<text>共计</text>
								<text style="margin: 0 4px;">{{paging.totalCount}}</text>
								<text>条</text>
							</text>
						</view>

						<view v-else>
							已选：{{selectedData.length}}
						</view>
					</view>
					<view class="operBtn">

						<u-row gutter="10" v-if="ShowSelect">
							<u-col span="6">
								<u-button class="CommonBtnSize" type="info" plain hairline text="取消"
									@click="cancelBtn"></u-button>
							</u-col>
							<u-col span="6">
								<u-button class="CommonBtnSize" type="primary" :throttleTime="2000" text="删除"
									@click="tapMoreBtn"></u-button>
							</u-col>
						</u-row>

					</view>


				</view>

			</template>
		</z-paging>

	</view>
</template>

<script>
	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;
	import DB from '@/uni_modules/mc-ui/components/m-sqlite/js_sdk/sqlite.js';
	export default {
		data() {
			return {
				titleName: '草稿箱',
				moduleName: '销售订单', // 模块名
				tableKeyName: '', // 表名
				tableData: [],
				listData: [],
				formMenus: [
					// {
					// 	name: '打开数据库',
					// 	value: '',
					// 	icon: 'order',
					// 	show: true,
					// 	FunName: 'openSQL'
					// }, {
					// 	name: '关闭数据库',
					// 	value: '',
					// 	icon: 'order',
					// 	show: true,
					// 	FunName: 'closeSQL'
					// },
					{
						name: '批量删除',
						value: '',
						icon: 'share-fill',
						show: true,
						FunName: 'deleteInBulk'
					}, {
						name: '一键删除',
						value: '',
						icon: 'trash-fill',
						show: true,
						FunName: 'deleteAllInBulk'
					},
				],

				paging: {
					totalCount: 0,
				},
				ShowSelect: false,
				selectedData: [], // 已选数据
				selectedDataID: [],
			};
		},
		onLoad(option) {
			let UserInfo = JSON.parse(this.Request.UserInfo());
			if (!this.$utils.isEmpty(option)) {
				this.titleName = option['titleName'] + '草稿箱';

				// 表名
				this.tableKeyName = 'appAccount_' + UserInfo.Business + '_' + UserInfo.UserID;

				this.openSQL();

			}
		},
		mounted() {
			let that = this;
			uni.$on('refreshDraftInfo', function() {
				that.tableData = [];
				that.searchDraft();
			})
		},
		onUnload() {
			this.closeSQL();
			uni.$off('refreshDraftInfo');
		},
		methods: {
			goBack(str) {

				if (str == 'close') {
					let routes = getCurrentPages(); //当前页面栈

					let routePageCurrent = this.$store.state.appConfigInfo.routePageCurrent;

					let backNum = routes.length - routePageCurrent;
					uni.navigateBack({
						delta: backNum
					})

				} else {
					uni.navigateBack();
				}

			},
			CheckedBack(data) {
				let flag = this.selectedDataID.includes(data.id);

				return flag;
			},
			cancelBtn() { // 取消按钮
				this.ShowSelect = false; // 关闭复选框
				this.selectedData = []; // 清空已选数据
				this.selectedDataID = [];
			},
			tapMoreBtn() { // 删除按钮
				let selectedDataID = this.selectedDataID.join(',');

				this.deleteMoreTableData(selectedDataID);

			},
			OpenSelectCellPopup() { // 点击已选数，查看批量数据

			},
			TapPopup(data) { // 执行下拉方法
				this[data.FunName]();
			},
			deleteInBulk() { // 点击批量删除按钮
				if (this.tableData.length) {
					// 开启多选
					this.ShowSelect = true;
				} else {
					this.$utils.msg('无可选内容');
				}
			},
			deleteAllInBulk() { // 一键删除
				let that = this;
				if (!this.tableData.length) {
					return this.$utils.msg('无需清除内容');
				};

				layer.confirm('确切全部删除吗？', {
					title: '提示'
				}, function(ret) {
					console.log(ret)
					if (ret.action == 'confirm') {
						let open = DB.isOpen();
						if (open) {
							DB.deleteTableData(that.tableKeyName, "detailTitle", that.titleName.replace('草稿箱', ''))
								.then(res => {
									that.showToast("删除表数据成功");
									that.$refs.paging.refresh();
								})
								.catch(error => {
									console.log("删除失败", error);
								});
						} else {
							that.showToast("数据库未打开");
						}
					}
				});

			},
			toFormEdit(data) { // 点击cell


				if (this.ShowSelect) {

					const index = this.selectedDataID.findIndex(item => item == data.id);

					if (index == -1) {
						// 没有查到数据
						this.selectedDataID.push(data.id);
						this.selectedData.push(data);
					} else {
						this.selectedDataID.splice(index, 1);
						this.selectedData.splice(index, 1);
					}


				} else { // 点击前往新增编辑

					// 参数
					var returnData = {
						id: data.id,
						detailTitle: data.detailTitle,
						detailName: data.detailName,
						keyName: data.keyName,
						keyValue: 0,
						dataInfo: {
							formData: JSON.parse(data.formData),
							// 子表数据
							childListData: JSON.parse(data.tableData),
							// waitKeyName: 'ClientID'

						}
					}

					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'MenuDetail',
						data: returnData
					});

					uni.navigateTo({
						url: '/commonPage/Form/Edit' + '?origin=draft'
					})
				}

			},

			searchDraft() {
				let that = this;
				let open = DB.isOpen();
				if (open) {
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					DB.selectTableData(this.tableKeyName, 'detailTitle', this.titleName.replace('草稿箱', ''))
						.then(res => {
							if (res.length == 0) {
								this.ShowSelect = false;
							}
							that.paging.totalCount = res.length;
							console.log(res);

							that.$refs.paging.complete(res);
							that.$forceUpdate();
						})
						.catch(error => {
							that.$refs.paging.complete([])
							// that.$refs.paging.complete(false)
							console.log("查询失败", error);
						});
				} else {
					that.$refs.paging.complete(false)
					this.showToast("数据库未打开");
				}
			},
			// 打开数据库
			openSQL() {
				let that = this;
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				console.log(open)
				if (!open) {
					DB.openSqlite()
						.then(res => {
							// console.log("数据库已打开");

							that.searchDraft();

							that.$forceUpdate();
						})
						.catch(error => {
							console.log("数据库开启失败");
						});
				} else {
					that.searchDraft();
							that.$forceUpdate();
				}
			},

			// 关闭数据库
			closeSQL() {
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				if (open) {
					DB.closeSqlite()
						.then(res => {
							// console.log("数据库已关闭");
						})
						.catch(error => {
							// console.log("数据库关闭失败");
						});
				}
			},

			// 查询表数据


			deleteDropTable() { // 删除表
				DB.dropTable(this.tableKeyName).then(res => {
						this.showToast("删除表成功");
					})
					.catch(error => {
						console.log("删除失败", error);
					});
			},
			// 删除表数据
			deleteMoreTableData(IdData) {
				let open = DB.isOpen();
				if (open) {
					DB.deleteMoreTableData(this.tableKeyName, "id", IdData)
						.then(res => {
							this.showToast("删除表数据成功");
							this.$refs.paging.refresh();
						})
						.catch(error => {
							console.log("删除失败", error);
						});
				} else {
					this.showToast("数据库未打开");
				}
			},





			// 提示框
			showToast: function(str) {
				uni.showToast({
					icon: "none",
					title: str,
					mask: true
				});
			},

			// 时间戳转年月日
			formatDate(data) {
				let now = new Date(data);
				var year = now.getFullYear(); //取得4位数的年份
				var month =
					now.getMonth() + 1 < 10 ?
					"0" + (now.getMonth() + 1) :
					now.getMonth() + 1;
				var date = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
				var hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
				var minute =
					now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
				var second =
					now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
				return (
					year +
					"-" +
					month +
					"-" +
					date +
					" " +
					hour +
					":" +
					minute +
					":" +
					second
				);
			}

		}
	}
</script>

<style lang="scss" scoped>
	.content {
		height: 100vh;
		background-color: #f2f2f2;

		uni-button {
			margin-left: initial !important;
			margin-right: initial !important;
		}


		.cellHover {
			background-color: #e7e7e7 !important;
		}

		.CellBox {
			// height: 60px;
			// line-height: 60px;
			min-height: 60px;
			padding: 0 10px 0 20px;
			background-color: #fff;
			border-bottom: 1px solid #e7e7e7;


			.ordinalBox {
				width: fit-content;
				min-width: 20px;
				height: 20px;
				line-height: 20px;
				text-align: center;
				border-radius: 4px;
				background-color: #51d0d0;
				margin-right: 8px;
				color: #fff;
				font-weight: 600;
			}
		}

		.bottomTool {
			background: #fff;
			padding: 15rpx;
			border-top: 2px solid #f2f2f2;
		}

		.operTotal {
			font-size: 14px;
			color: #333;
			min-height: 40px;
		}

		.operBtn {
			width: fit-content;
		}
	}
</style>